package com.jt.project;

import com.jt.datasource.JedisDataSource;
import redis.clients.jedis.Jedis;

import java.util.Set;

public class VoteDemo01 {
    public static void main(String[] args) {
        //活动
        String activityId="101";
        //用户
        String user1="2001";
        String user2="2002";
        String user3="2003";
        //投票
        boolean flag1=doVote(activityId,user1);
        boolean flag2=doVote(activityId,user2);
        boolean flag3=doVote(activityId,user3);
        boolean flag4=doVote(activityId,user1);
        //总投票数
        long count=doCount(activityId);
        System.out.println("票数:"+count);
        //谁参与
        Set<String> userIds=doGetUsers(activityId);
        System.out.println("活动的用户为:"+userIds);
    }

    private static Set<String> doGetUsers(String activityId) {
        Jedis jedis= JedisDataSource.getConnection();
        Set<String> members = jedis.smembers(activityId);
        jedis.close();
        return members;
    }

    private static long doCount(String activityId) {
        Jedis jedis=JedisDataSource.getConnection();
        Long count = jedis.scard(activityId);
        jedis.close();
        return count;
    }

    private static boolean doVote(String activityId, String userId) {
        Jedis jedis= JedisDataSource.getConnection();
        Boolean flag = jedis.sismember(activityId, userId);
        if (flag){
            jedis.srem(activityId, userId);
            flag=false;
        }else {
            jedis.sadd(activityId, userId);
            flag=true;
        }
        jedis.close();
        return flag;
    }
}
